package com.corpgovernment.common.utils;
import com.ctrip.framework.apollo.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;

@Slf4j
public class DESUtil {
    private String key;

    public DESUtil(String key) {
        this.key = key;
    }

    public String getKey() {
        return key;
    }

    public String encryptStr(String strMing)
            throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
        SecretKeySpec key = new SecretKeySpec(this.getKey().getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
        byte[] encryptedData = cipher.doFinal(strMing.getBytes());

        return new BASE64Encoder().encode(encryptedData);
    }

    public String decryptStr(String decryptString)
            throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
            InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        byte[] byteMi = new BASE64Decoder().decodeBuffer(decryptString);
        IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
        SecretKeySpec key = new SecretKeySpec(this.getKey().getBytes(), "DES");
        Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
        byte decryptedData[] = cipher.doFinal(byteMi);

        return new String(decryptedData);
    }

    /**
     * TripleDES加密
     *
     * @param content 内容
     * @return 加密后的字符, 加密失败则返回原字符串
     */
    public String desEncrypt_CBC(String content) {
        if (StringUtils.isBlank(content)) {
            return null;
        }
        try {
            String md5Key = md5(key);
            byte[] bufKey = md5Key.substring(0, 24).getBytes();
            byte[] bufIV = md5Key.substring(24).getBytes();

            SecretKey deskey = new SecretKeySpec(bufKey, "DESede");
            Cipher cip = Cipher.getInstance("DESede/CBC/PKCS5Padding");//Cipher.getInstance("DES");
            AlgorithmParameterSpec iv2 = new IvParameterSpec(bufIV);
            cip.init(Cipher.ENCRYPT_MODE, deskey, iv2);//IV的方式
            String result = new String(Base64.encodeBase64(cip.doFinal(content.getBytes())));
            return result;
        } catch (Exception e) {
            //如有错就返回null
            log.info("DES加密失败: {}", e.getMessage());
        }
        return content;
    }

    private String md5(String key) {
        try {
            MessageDigest md5 = null;
            try {
                md5 = MessageDigest.getInstance("MD5");
            } catch (Exception var8) {
                return "";
            }

            char[] charArray = key.toCharArray();
            byte[] byteArray = new byte[charArray.length];

            for(int i = 0; i < charArray.length; ++i) {
                byteArray[i] = (byte)charArray[i];
            }

            byte[] md5Bytes = md5.digest(byteArray);
            StringBuffer hexValue = new StringBuffer();

            for(int i = 0; i < md5Bytes.length; ++i) {
                int val = md5Bytes[i] & 255;
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
            return hexValue.toString();
        } catch (Exception var9) {
            var9.printStackTrace();
            return "";
        }
    }
}
